package com.biallen.datastructure.stack;

import java.util.Scanner;

public class CaculateDemo {

    public static void main(String[] args) {

        /**
         * 后续优化 加 小括号的 运算
         */
        String expression="20*3+5-6";
        ArrayStack numStack = new ArrayStack(10);
        ArrayStack operStack = new ArrayStack(10);
        int index  = 0;
        int num1 =0;
        int num2 =0;
        int res = 0;
        char ch  =' ';
        int oper =0;
        String keepNum  = "";
        while ( true){
            ch = expression.substring(index,index+1).charAt(0);
            if(operStack.isOper(ch)){
                if(!operStack.isEmpty()){
                    //当前操作符的优先级小于栈顶的操作符的优先级 则需要先计算 栈顶的操作:取 数栈 前两个值 再去 符号栈顶 计算
                    //并将计算的结果压入数栈 当前的操作符压入符号栈
                    if(operStack.priority(ch)<= operStack.priority(operStack.peek())){
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        res = operStack.culcate(num1,num2,operStack.pop());
                        numStack.push(res);
                        operStack.push(ch);
                    }else {
                        operStack.push(ch);
                    }
                }else {
                    operStack.push(ch);
                }
            }else {
                //numStack.push(ch-48);
                keepNum+=ch;
                if(index == expression.length()-1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    if(numStack.isOper(expression.substring(index+1,index+2).charAt(0))){
                        numStack.push(Integer.parseInt(keepNum));
                        keepNum ="";
                    }
                }
            }

            index++;
            if(index >= expression.length()){
                break;
            }
        }

        while (true){

            if(operStack.isEmpty()){
                break;
            }

            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res  =  operStack.culcate(num1,num2,oper);
            numStack.push(res);
        }
        System.out.println("最终计算结果:"+ numStack.pop());
    }
}
